#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "sem.h"
#define SEND_OK 0xAA

typedef struct {

	uint8_t temp[2];	 //温度	
	uint8_t hum[2];		 //湿度
	uint8_t x;			 //三轴信息
	uint8_t y;			 
	uint8_t z;			 
	uint32_t ill;		 //光照
	uint32_t bet;		 //电池电量
	uint32_t adc; 		 //电位器信息
}MSG;

int main (int argc, char *argv[])
{
    int server_fd, connect_fd;
    struct sockaddr_in server_addr;
    int shmid;
	int semid;
    MSG *pmsg;
    MSG msg = {0};

  
    key_t key;
    key = ftok("/", 'a');
    if (key < 0)
    {
        perror("fail to ftok");
        exit(-1);
    }
	fisrt_init_sem(&semid, &key);//初始化信号量
	init_sem(semid, 0, 1);
	
    shmid = shmget(key, sizeof(MSG), IPC_CREAT | IPC_EXCL | 0777);
     if (shmid < 0)
    {
        if (errno = EEXIST)
        {
            shmid = shmget(key, 0, 0777);
        }
        else
        {
            perror("fail to shmget");
            exit(-1);
        }
    }
    
    if ((pmsg = (MSG *)shmat(shmid, NULL, 0)) == (MSG *)-1)//映射共享内存
    {
        perror("fail to shmat");
        exit(-1);
    }
    
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[2]));
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0)
    {
        perror("socket error");
        exit(-1);
    }
    
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("fail to bind");
        exit(-1);
    }
    
    if (listen(server_fd, 5) < 0)
    {
        perror("fail to listen");
        exit(-1);
    }
//    puts("等待客户端连接");
    if ((connect_fd = accept(server_fd, NULL, NULL)) < 0)
    {
        perror("fail to accept");
        exit(-1);
    }
//    puts("客户端已连接");
    while(1)
    {
		int ret = 0;
		ret = recv(connect_fd, &msg, sizeof(msg), 0);
        if(ret)//接收客户端穿过来的东西
        {   //接收到的东西写入共享内存

            printf("%uF,%uF,%u%%,%u%%,%um/(s*s),%um/(s*s),%um/(s*s),%uLUX,%umV,%umV\n", msg.temp[0], msg.temp[1], msg.hum[0], msg.hum[1], msg.x, msg.y, msg.z, msg.ill, msg.bet, msg.adc);//看看有木有收到
			
			sem_p(semid, 0);
            
 			pmsg->temp[0] = msg.temp[0];
            pmsg->temp[1] =msg.temp[1];
            pmsg->hum[0] = msg.hum[0];
            pmsg->hum[1] = msg.hum[1];
            pmsg->x = msg.x;
            pmsg->y = msg.y;
            pmsg->z = msg.z;
            pmsg->ill = msg.ill;
            pmsg->bet = msg.bet;
            pmsg->adc = msg.adc;//*/
            

			sem_v(semid, 0);
        }
        else
        {
            puts("recv error!");
        }
    }
    
    return 0;
}
